<template>
  <div class="user-profile">
    <!-- 未绑定信息时显示 -->
    <el-card v-if="!userInfo" class="profile-card">
      <div slot="header">
        <span>账号绑定</span>
      </div>
      <div class="bind-section">
        <p class="bind-tip">您的账号尚未绑定个人信息，请选择绑定类型：</p>
        <div class="bind-options">
          <el-radio-group v-model="bindForm.userType">
            <el-radio :label="1">员工</el-radio>
            <el-radio :label="2">农户</el-radio>
          </el-radio-group>
        </div>
        <div class="bind-actions">
          <el-button type="primary" @click="handleBind">立即绑定</el-button>
        </div>
      </div>
    </el-card>

    <!-- 已绑定信息时显示 -->
    <el-card v-else class="profile-card">
      <div slot="header">
        <span>个人信息</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="handleEdit"
        >
          {{ isEditing ? '取消' : '修改' }}
        </el-button>
      </div>

      <!-- 员工信息表单 -->
      <el-form 
        v-if="isEmployee"
        ref="profileForm"
        :model="employeeForm"
        :rules="employeeRules"
        :disabled="!isEditing"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="employeeName">
          <el-input v-model="employeeForm.employeeName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="employeeForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="employeeForm.birthDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="employeeForm.hireDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="employeeForm.position" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="employeeForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email"></el-input>
        </el-form-item>
      </el-form>

      <!-- 农户信息表单 -->
      <el-form 
        v-else
        ref="profileForm"
        :model="growerForm"
        :rules="growerRules"
        :disabled="!isEditing"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="growerName">
          <el-input v-model="growerForm.growerName"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="growerForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="growerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="growerForm.address"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input v-model="growerForm.deptName" disabled></el-input>
        </el-form-item>
      </el-form>

      <div class="form-actions" v-if="isEditing">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleEdit">取消</el-button>
      </div>

      <!-- 修改密码部分 -->
      <div class="password-section">
        <el-divider>修改密码</el-divider>
        <el-button type="text" @click="showPasswordDialog">修改密码</el-button>
      </div>

      <!-- 在个人信息卡片后添加角色管理卡片 -->
      <el-card class="profile-card" style="margin-top: 20px;">
        <div slot="header">
          <span>角色管理</span>
        </div>

        <!-- 当前角色展示 -->
        <div class="role-section">
          <h4>当前角色</h4>
          <div class="current-roles">
            <el-tag
              v-for="role in userRoles"
              :key="role.roleId"
              style="margin-right: 10px; margin-bottom: 10px;"
            >
              {{ role.roleName }}
            </el-tag>
          </div>
        </div>

        <!-- 角色申请按钮 -->
        <div class="role-actions">
          <el-button type="primary" @click="showRoleApplyDialog">申请新角色</el-button>
          <el-button type="info" @click="showMyApplies">我的申请记录</el-button>
          <el-button type="warning" @click="showApprovalList">待我审批</el-button>
        </div>
      </el-card>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="400px">
      <el-form 
        ref="passwordForm"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordChange">确认修改</el-button>
      </div>
    </el-dialog>

    <!-- 绑定信息选择对话框 -->
    <el-dialog :title="bindDialogTitle" :visible.sync="bindDialogVisible" width="90%" append-to-body>
      <!-- 员工选择 -->
      <employee-manager
        v-if="bindForm.userType === 1"
        ref="employeeManager"
        :show-select="true"
        @select="handleEmployeeSelect"
      />
      
      <!-- 农户选择 -->
      <grower-manager
        v-else
        ref="growerManager"
        :show-select="true"
        @select="handleGrowerSelect"
      />
    </el-dialog>

    <!-- 角色申请对话框 -->
    <el-dialog title="申请新角色" :visible.sync="roleApplyDialogVisible" width="500px">
      <el-form ref="roleApplyForm" :model="roleApplyForm" :rules="roleApplyRules" label-width="100px">
        <el-form-item label="申请角色" prop="roleId">
          <el-select v-model="roleApplyForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in availableRoles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批主管" prop="supervisorId">
          <el-input 
            v-model="selectedSupervisorName" 
            placeholder="请选择审批主管" 
            readonly
            @click.native="showSupervisorSelect"
          >
            <el-button slot="append" icon="el-icon-search" @click="showSupervisorSelect"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="申请理由" prop="applyReason">
          <el-input
            type="textarea"
            v-model="roleApplyForm.applyReason"
            :rows="4"
            placeholder="请详细说明申请理由"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="roleApplyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleApply">提交申请</el-button>
      </div>
    </el-dialog>

    <!-- 主管选择对话框 -->
    <el-dialog 
      title="选择审批主管" 
      :visible.sync="supervisorSelectVisible" 
      width="90%" 
      append-to-body
    >
      <employee-manager
        ref="supervisorSelector"
        :show-select="true"
        @select="handleSupervisorSelect"
      />
    </el-dialog>

    <!-- 我的申请记录对话框 -->
    <el-dialog title="我的申请记录" :visible.sync="myAppliesDialogVisible" width="800px">
      <el-table :data="myApplies" border>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column prop="roleName" label="申请角色" width="120" />
        <el-table-column prop="applyReason" label="申请理由" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approveRemark" label="审批意见" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleMyAppliesSizeChange"
          @current-change="handleMyAppliesCurrentChange"
          :current-page="myAppliesQuery.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="myAppliesQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="myAppliesTotal"
        />
      </div>
    </el-dialog>

    <!-- 待审批列表对话框 -->
    <el-dialog title="待审批列表" :visible.sync="approvalListDialogVisible" width="900px">
      <el-table :data="approvalList" border>
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="申请人" width="120" />
        <el-table-column prop="roleName" label="申请角色" width="120" />
        <el-table-column prop="applyReason" label="申请理由" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="text"
              @click="handleApprove(scope.row)"
            >审批</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleApprovalListSizeChange"
          @current-change="handleApprovalListCurrentChange"
          :current-page="approvalListQuery.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="approvalListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="approvalListTotal"
        />
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批" :visible.sync="approveDialogVisible" width="500px">
      <el-form ref="approveForm" :model="approveForm" :rules="approveRules" label-width="100px">
        <el-form-item label="审批结果" prop="approved">
          <el-radio-group v-model="approveForm.approved">
            <el-radio :label="1">同意</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="approveRemark">
          <el-input
            type="textarea"
            v-model="approveForm.approveRemark"
            :rows="4"
            placeholder="请填写审批意见"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import EmployeeManager from '@/views/system/EmployeeManager.vue'
import GrowerManager from '@/views/basic/Grower.vue'

export default {
  name: 'UserProfile',
  components: {
    EmployeeManager,
    GrowerManager
  },
  data() {
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    // 验证身份证号
    const validateIdCard = (rule, value, callback) => {
      if (value && !/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/.test(value)) {
        callback(new Error('请输入正确的身份证号'))
      } else {
        callback()
      }
    }
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      isEditing: false,
      userInfo: null,
      // 员工表单
      employeeForm: {
        employeeId: undefined,
        employeeName: '',
        gender: 1,
        birthDate: '',
        hireDate: '',
        position: '',
        phone: '',
        email: '',
        isActive: 1
      },
      // 农户表单
      growerForm: {
        growerId: undefined,
        growerName: '',
        idCard: '',
        phone: '',
        address: '',
        deptId: undefined,
        deptName: ''
      },
      // 员工表单校验规则
      employeeRules: {
        employeeName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 农户表单校验规则
      growerRules: {
        growerName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ]
      },
      // 修改密码相关
      passwordDialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 绑定相关
      bindDialogVisible: false,
      bindForm: {
        userType: 1,
        refId: undefined
      },
      bindRules: {
        refId: [
          { required: true, message: '请选择要绑定的信息', trigger: 'change' }
        ]
      },
      bindOptions: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showAddForm: false,
      searchForm: {
        growerName: '',
        idCard: '',
        employeeName: '',
        phone: ''
      },
      addForm: {
        name: '',
        idCard: '',
        phone: '',
        email: '',
        position: '',
        address: '',
        deptId: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ]
      },
      deptOptions: [],
      // 角色管理相关
      roleApplyDialogVisible: false,
      roleApplyForm: {
        roleId: '',
        supervisorId: '',
        applyReason: ''
      },
      roleApplyRules: {
        roleId: [
          { required: true, message: '请选择要申请的角色', trigger: 'change' }
        ],
        supervisorId: [
          { required: true, message: '请选择审批主管', trigger: 'change' }
        ],
        applyReason: [
          { required: true, message: '请填写申请理由', trigger: 'blur' }
        ]
      },
      myAppliesDialogVisible: false,
      myApplies: [],
      myAppliesQuery: {
        current: 1,
        size: 10
      },
      myAppliesTotal: 0,
      approvalListDialogVisible: false,
      approvalList: [],
      approvalListQuery: {
        current: 1,
        size: 10
      },
      approvalListTotal: 0,
      approveDialogVisible: false,
      approveForm: {
        approved: 0,
        approveRemark: ''
      },
      approveRules: {
        approved: [
          { required: true, message: '请选择审批结果', trigger: 'change' }
        ],
        approveRemark: [
          { required: true, message: '请填写审批意见', trigger: 'blur' }
        ]
      },
      userRoles: [],
      availableRoles: [],
      supervisorSelectVisible: false,
      selectedSupervisorName: '',
      currentApply: null,
      roleInfo: {
        SUPER_ADMIN: { id: 1, roleName: '超级管理员', roleCode: 'SUPER_ADMIN' },
        SYS_ADMIN: { id: 2, roleName: '系统管理员', roleCode: 'SYS_ADMIN' },
        NORMAL_USER: { id: 3, roleName: '普通用户', roleCode: 'NORMAL_USER' },
        LIAISON_OFFICER: { id: 4, roleName: '联络员', roleCode: 'LIAISON_OFFICER' },
        COUNSELOR: { id: 5, roleName: '辅导员', roleCode: 'COUNSELOR' },
        SEEDLING_MANAGER: { id: 6, roleName: '育苗点负责人', roleCode: 'SEEDLING_MANAGER' },
        FARMER: { id: 7, roleName: '农户', roleCode: 'FARMER' }
      }
    }
  },
  computed: {
    isEmployee() {
      return this.userInfo && 'employeeId' in this.userInfo
    },
    bindDialogTitle() {
      return this.bindForm.userType === 1 ? '绑定员工信息' : '绑定农户信息'
    }
  },
  created() {
    this.fetchUserInfo()
    this.fetchUserRoles()
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await request.get('/base/user/info')
        this.userInfo = response
        if (this.userInfo) {
          if (this.isEmployee) {
            this.employeeForm = { ...this.userInfo }
          } else {
            this.growerForm = { ...this.userInfo }
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },

    // 切换编辑状态
    handleEdit() {
      if (this.isEditing) {
        this.fetchUserInfo() // 取消编辑时重新获取数据
      }
      this.isEditing = !this.isEditing
    },

    // 提交个人信息修改
    handleSubmit() {
      const form = this.isEmployee ? this.employeeForm : this.growerForm
      const url = this.isEmployee ? '/employees' : '/growers'
      
      this.$refs.profileForm.validate(async valid => {
        if (valid) {
          try {
            await request.put(url, form)
            this.$message.success('保存成功')
            this.isEditing = false
            this.fetchUserInfo()
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 显示修改密码对话框
    showPasswordDialog() {
      this.passwordDialogVisible = true
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    },

    // 提交密码修改
    async handlePasswordChange() {
      try {
        await this.$refs.passwordForm.validate()
        await request.post('/auth/password', {
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword,
          confirmPassword: this.passwordForm.confirmPassword
        })
        this.$message.success('密码修改成功，请重新登录')
        this.passwordDialogVisible = false
        // 直接跳转到登录页
        this.$router.push('/login')
      } catch (error) {
        if (error !== false) {
          console.error('密码修改失败:', error)
          this.$message.error('密码修改失败')
        }
      }
    },

    // 合并后的handleBind方法
    async handleBind() {
      this.bindDialogVisible = true
      if (this.bindForm.userType === 1) {
        // 等待组件挂载完成后再调用方法
        this.$nextTick(() => {
          if (this.$refs.employeeManager) {
            this.$refs.employeeManager.getList()
          }
        })
      } else {
        // 等待组件挂载完成后再调用方法
        this.$nextTick(() => {
          if (this.$refs.growerManager) {
            this.$refs.growerManager.getList()
          }
        })
      }
    },

    async fetchUnbindList() {
      try {
        this.loading = true
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }

        if (this.bindForm.userType === 2) {
          // 农户搜索参数
          if (this.searchForm.growerName) params.growerName = this.searchForm.growerName
          if (this.searchForm.idCard) params.idCard = this.searchForm.idCard
          const response = await request.get('/growers/unbind', { params })
          this.bindOptions = response.records
          this.total = response.total
        } else {
          // 员工搜索参数
          if (this.searchForm.employeeName) params.employeeName = this.searchForm.employeeName
          const response = await request.get('/employees/page', { params })
          // 过滤掉已绑定的员工
          this.bindOptions = response.records.filter(employee => !employee.userId)
          this.total = this.bindOptions.length
        }
      } catch (error) {
        console.error('获取未绑定列表失败:', error)
        this.$message.error('获取未绑定列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.fetchUnbindList()
    },

    resetSearch() {
      this.searchForm = {
        growerName: '',
        idCard: '',
        employeeName: '',
        phone: ''
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUnbindList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUnbindList()
    },

    handleRowClick(row) {
      this.handleSelect(row)
    },

    async handleSelect(row) {
      try {
        const params = {
          userType: this.bindForm.userType,
          refId: this.bindForm.userType === 1 ? row.employeeId : row.growerId
        }
        await request.post('/base/user/bind', params)
        this.$message.success('绑定成功')
        this.bindDialogVisible = false
        // 刷新用户信息
        this.fetchUserInfo()
      } catch (error) {
        console.error('绑定失败:', error)
        this.$message.error('绑定失败')
      }
    },

    handleCancel() {
      if (this.showAddForm) {
        this.showAddForm = false
        this.addForm = {
          name: '',
          idCard: '',
          phone: '',
          email: '',
          position: '',
          address: '',
          deptId: null
        }
      } else {
        this.bindDialogVisible = false
      }
    },

    async handleAddSubmit() {
      try {
        await this.$refs.addForm.validate()
        
        const params = {
          ...this.addForm
        }

        if (this.bindForm.userType === 2) {
          // 新增农户
          params.growerName = params.name
          delete params.name
          await request.post('/growers', params)
        } else {
          // 新增员工
          params.employeeName = params.name
          delete params.name
          await request.post('/employees', params)
        }

        this.$message.success('添加成功')
        this.showAddForm = false
        this.fetchUnbindList()
      } catch (error) {
        if (error !== false) {
          console.error('添加失败:', error)
          this.$message.error('添加失败')
        }
      }
    },

    async handleEmployeeSelect(employee) {
      try {
        const params = {
          userType: this.bindForm.userType,
          refId: employee.employeeId
        }
        await request.post('/base/user/bind', params)
        this.$message.success('绑定成功')
        this.bindDialogVisible = false
        // 刷新用户信息
        this.fetchUserInfo()
      } catch (error) {
        console.error('绑定失败:', error)
        this.$message.error('绑定失败')
      }
    },

    async handleGrowerSelect(grower) {
      try {
        const params = {
          userType: this.bindForm.userType,
          refId: grower.growerId
        }
        await request.post('/base/user/bind', params)
        this.$message.success('绑定成功')
        this.bindDialogVisible = false
        // 刷新用户信息
        this.fetchUserInfo()
      } catch (error) {
        console.error('绑定失败:', error)
        this.$message.error('绑定失败')
      }
    },

    // 获取用户角色
    async fetchUserRoles() {
      try {
        const roleCode = await request.get('/role-apply/current-role')
        this.userRoles = [this.roleInfo[roleCode] || { roleName: '未知角色', roleCode }]
      } catch (error) {
        console.error('获取用户角色失败:', error)
        this.$message.error('获取用户角色失败')
      }
    },

    // 获取可用角色
    async fetchAvailableRoles() {
      // 直接使用本地roleInfo数据
      this.availableRoles = Object.values(this.roleInfo)
    },

    // 获取审批主管列表
    async fetchSupervisors() {
      try {
        const response = await request.get('/employees/supervisors')
        this.supervisors = response
      } catch (error) {
        console.error('获取审批主管失败:', error)
        this.$message.error('获取审批主管失败')
      }
    },

    // 获取我的申请记录
    async fetchMyApplies() {
      try {
        const response = await request.get('/role-apply/my-applies', {
          params: {
            current: this.myAppliesQuery.current,
            size: this.myAppliesQuery.size
          }
        })
        // 直接使用 response，因为响应已经被全局处理
        this.myApplies = response.records
        this.myAppliesTotal = response.total
      } catch (error) {
        console.error('获取我的申请记录失败:', error)
        this.$message.error('获取我的申请记录失败')
      }
    },

    // 获取待审批列表
    async fetchApprovalList() {
      try {
        const response = await request.get('/role-apply/approval-list', {
          params: {
            current: this.approvalListQuery.current,
            size: this.approvalListQuery.size
          }
        })
        // 直接使用 response，因为响应已经被全局处理
        this.approvalList = response.records
        this.approvalListTotal = response.total
      } catch (error) {
        console.error('获取待审批列表失败:', error)
        this.$message.error('获取待审批列表失败')
      }
    },

    // 提交角色申请
    async submitRoleApply() {
      try {
        await this.$refs.roleApplyForm.validate()
        await request.post('/role-apply', this.roleApplyForm)
        this.$message.success('角色申请提交成功')
        this.roleApplyDialogVisible = false
        this.fetchMyApplies()
      } catch (error) {
        if (error !== false) {
          console.error('角色申请提交失败:', error)
          this.$message.error('角色申请提交失败')
        }
      }
    },

    // 提交审批
    async submitApprove() {
      try {
        await this.$refs.approveForm.validate()
        const { id } = this.currentApply
        await request.post(`/role-apply/approve/${id}`, {
          approved: this.approveForm.approved,
          approveRemark: this.approveForm.approveRemark
        })
        this.$message.success('审批提交成功')
        this.approveDialogVisible = false
        this.fetchApprovalList()
      } catch (error) {
        if (error !== false) {
          console.error('审批提交失败:', error)
          this.$message.error('审批提交失败')
        }
      }
    },

    // 处理审批操作
    handleApprove(row) {
      this.currentApply = row
      this.approveForm = {
        approved: 1,
        approveRemark: ''
      }
      this.approveDialogVisible = true
    },

    getStatusType(status) {
      switch (status) {
        case 0:
          return 'info'
        case 1:
          return 'success'
        case 2:
          return 'warning'
        default:
          return 'info'
      }
    },

    getStatusText(status) {
      switch (status) {
        case 0:
          return '待审批'
        case 1:
          return '已通过'
        case 2:
          return '已拒绝'
        default:
          return '未知状态'
      }
    },

    // 显示主管选择对话框
    showSupervisorSelect() {
      this.supervisorSelectVisible = true
      this.$nextTick(() => {
        if (this.$refs.supervisorSelector) {
          this.$refs.supervisorSelector.getList()
        }
      })
    },

    // 处理主管选择
    handleSupervisorSelect(employee) {
      this.roleApplyForm.supervisorId = employee.employeeId
      this.selectedSupervisorName = employee.employeeName
      this.supervisorSelectVisible = false
    },

    // 显示角色申请对话框
    async showRoleApplyDialog() {
      await this.fetchAvailableRoles()
      this.roleApplyForm = {
        roleId: '',
        supervisorId: '',
        applyReason: ''
      }
      this.selectedSupervisorName = ''
      this.roleApplyDialogVisible = true
    },

    // 显示我的申请记录对话框
    async showMyApplies() {
      this.myAppliesQuery = {
        current: 1,
        size: 10
      }
      this.myAppliesDialogVisible = true
      await this.fetchMyApplies()
    },

    // 显示待审批列表对话框
    async showApprovalList() {
      this.approvalListQuery = {
        current: 1,
        size: 10
      }
      this.approvalListDialogVisible = true
      await this.fetchApprovalList()
    },

    // 处理我的申请记录分页
    handleMyAppliesSizeChange(val) {
      this.myAppliesQuery.size = val
      this.fetchMyApplies()
    },

    handleMyAppliesCurrentChange(val) {
      this.myAppliesQuery.current = val
      this.fetchMyApplies()
    },

    // 处理待审批列表分页
    handleApprovalListSizeChange(val) {
      this.approvalListQuery.size = val
      this.fetchApprovalList()
    },

    handleApprovalListCurrentChange(val) {
      this.approvalListQuery.current = val
      this.fetchApprovalList()
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-profile {
  padding: 20px;

  .profile-card {
    max-width: 800px;
    margin: 0 auto;
  }

  .bind-section {
    text-align: center;
    padding: 20px;

    .bind-tip {
      font-size: 16px;
      color: #606266;
      margin-bottom: 20px;
    }

    .bind-options {
      margin-bottom: 20px;
    }
  }

  .form-actions {
    margin-top: 20px;
    text-align: center;
  }

  .password-section {
    margin-top: 30px;
    text-align: center;
  }

  .search-section {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .role-section {
    margin-top: 20px;
    margin-bottom: 20px;

    h4 {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .current-roles {
      margin-bottom: 10px;
    }
  }

  .role-actions {
    margin-top: 20px;
    text-align: right;
  }
}

.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
  width: auto !important;
  height: auto !important;

  &[append-to-body] {
    position: fixed;
  }
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
  padding: 20px;
  height: auto !important;
  max-height: calc(90vh - 120px);
}

.el-dialog .el-dialog__header {
  padding: 20px;
  margin: 0;
}

.el-dialog .el-dialog__footer {
  padding: 20px;
  margin: 0;
}

.table-wrapper {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
  margin-bottom: 10px;
}

.el-table {
  width: 100% !important;
  height: 100%;
}

.pagination-container {
  padding: 10px 0;
  background: #fff;
  text-align: right;
  position: relative;
  z-index: 1;
}

// 修复嵌套对话框的样式
.el-dialog__wrapper {
  overflow: hidden;
  
  .el-dialog__wrapper {
    position: fixed;
    
    .el-dialog {
      margin: 0 auto !important;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
      left: 0;
      right: 0;
    }
  }
}

// 优化表单布局
.el-form {
  .el-form-item {
    margin-bottom: 22px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 优化按钮布局
.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style> 